#include "core.h"

Core::Core() {
    world_ = new World;
    sb_ = new SolidBar;
    torch_ = new Torch;
    draw_ = new Draw(world_->GetWorldRenderer());
    event_ = new SDL_Event;
}

Core::~Core() {
    delete world_;
    delete sb_;
    delete torch_;
    delete draw_;

    delete event_;
}

void Core::IsQuit() {
    IsQuit_ = true;
}

ZOOM Core::SetZoom(int x, int y) {
    // inner rect
    if (y <= sb_->GetRect()->y && x >= sb_->GetRect()->x && 
        y >= sb_->GetRect()->y + sb_->GetRect()->h && x <= sb_->GetRect()->x + sb_->GetRect()->w) {
        return SELF;
    }
    // 123
    if (y < sb_->GetRect()->y) {
        if (x < sb_->GetRect()->x) {
            return UL;
        }
        else if (x < sb_->GetRect()->x + sb_->GetRect()->w) {
            return U;
        }
        else {
            return UR;
        }
    }
    // 567
    else if (y > sb_->GetRect()->y + sb_->GetRect()->h) {
        if (x < sb_->GetRect()->x) {
            return LL;
        }
        else if (x < sb_->GetRect()->x + sb_->GetRect()->w) {
            return B;
        }
        else {
            return LR;
        }
    }
    // 408
    else {
        if (x < sb_->GetRect()->x) {
            return L;
        }
        else if (x < sb_->GetRect()->x + sb_->GetRect()->w) {
            return SELF;
        }
        else {
            return R;
        }
    }
}

void Core::EventHandle() {
    if (event_->type == SDL_QUIT) {
        IsQuit();
    }
    if (event_->type == SDL_MOUSEMOTION) {
        torch_ ->GetRect()->x = event_->motion.x - torch_->GetRect()->w/2;
        torch_ ->GetRect()->y = event_->motion.y - torch_->GetRect()->h/2;
    }
}

void Core::EventLoop() {
    sb_->SetRect(100, 100, 30, 30);
    torch_->SetRect(200, 200, 10, 10);
    while (!IsQuit_) {
        fps_time_ = SDL_GetTicks();
        while (SDL_PollEvent(event_)) {
            EventHandle();
        }
        SDL_RenderClear(world_->GetWorldRenderer());
        draw_->DrawRect(sb_);
        draw_->DrawRect(torch_);
        draw_->LinkRects(sb_, torch_);
        SDL_RenderPresent(world_->GetWorldRenderer());

        if (SDL_GetTicks() - fps_time_ < MIN_FPS_TIME_) {
            SDL_Delay(SDL_GetTicks() - fps_time_);
        }
    }
}

